import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { Text, TouchableOpacity, View, StyleSheet, Alert, Image, ActivityIndicator } from 'react-native';
import { Icon, List, ListItem, Button, FormInput, CheckBox } from 'react-native-elements';
import RefreshScrollView from './widgets/RefreshScrollView';
import { clearStorage } from './clientStorage';
import { NavigationActions } from 'react-navigation';
import { executor, primaryColor, toast, uploadImage } from './utils';
import ImagePicker from 'react-native-image-crop-picker';

const styles = StyleSheet.create({
  container: {
    padding: 16
  },
  marginTop: {
    marginVertical: 16
  },
  right: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center'
  },
  spaceBetween: {
    marginTop: 16,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  image: {
    width: 70,
    height: 70
  },
  row: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginTop: 16
  }
});

class PhotoUploadPage extends Component {
  static navigationOptions = ({screenProps, navigation}) => {
    return {
      title: `${screenProps.chinese?'订单':'Order'} #${navigation.state.params.displayId}`,
    };
  }
  state = {}
  onAdd = () => {
    ImagePicker.openCamera({width: 400, height: 400, compressImageMaxWidth: 400, compressImageMaxHeight: 400 })
      .then(({path}) => {
        if (!path) return;
        const files = this.state.files||[];
        const index = files.indexOf(path);
        if (index < 0) {
          this.setState({files:[...files, path]});
        }
      });
  }
  onUpload = () => {
    const { files } = this.state;
    if (!files||(files.length===0)) return toast('Please select a file to upload');

    executor(this.props.uploadOrderImage, files)
      .then(({res}) => {
        if (res) {
          this.props.navigation.goBack();
          toast('Photo uploaded');
        }
        this.setState({uploading: false});
      });
    this.setState({uploading: true}); 
  }
  render() {
    const { files, uploading } = this.state;

    return (
      <RefreshScrollView refetch={this.props.refetch}>
        <Button containerViewStyle={styles.marginTop} color='black' title='Add New Photo'
          backgroundColor='white' onPress={this.onAdd}/>
        <View style={styles.row}>
          {files&&files.map((uri, index) =>
            <TouchableOpacity key={index} onPress={()=>this.setState({files:[...files.slice(0,index), ...files.slice(index+1)]})}>
              <View style={styles.container}>
                <Text>{index+1}. photo added</Text>
                <Image style={styles.image} source={{uri}}/>
              </View>
            </TouchableOpacity>
          )}
        </View>
        {uploading?<ActivityIndicator/>:
          <Button containerViewStyle={styles.marginTop} color='black' title='Upload'
            backgroundColor='white' onPress={this.onUpload}/>
        }
      </RefreshScrollView>
    );
  }
}

export default compose(
  graphql(gql`
    mutation uploadOrderImage($orderId:String!,$images:[String]!) {
      uploadOrderImage(orderId:$orderId,images:$images)
    }
  `, {
    props: ({ownProps:{navigation:{state:{params:{orderId}}}}, mutate}) => {
      return {
        uploadOrderImage: (files) => {
          return Promise.all(files?files.map(uri=>uploadImage(uri)):[])
            .then(uploads => mutate({
              variables: {
                orderId,
                images: (uploads&&uploads.length>0)?uploads.map(upload=>upload.data):undefined
              }
            }));
        }
      };
    }
  })
)(PhotoUploadPage);

